<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/10
 * Time: 15:38
 */
namespace app\admin\controller;

use app\admin\model\Shop as ShopModel;
use think\Db;
use think\Exception;

class Shop extends Base{

    protected static $err_code = 0;
    /**
     * 空操作
     */
    public function _empty(){
        $this->redirect('admin/login');
    }

    /**
     * 店铺管理
     */
    public function shop_list(){
        $page_param = input('param.');
        if (isset($page_param['page']) && $page_param['page'] > 0)
            unset($page_param['page']);
        $gets['province'] = request()->get('province','');//省份
        $gets['shop_name'] = request()->get('shop_name','');//店铺关键词
        $where = [];
        if ($gets['province'] !=''){
            $where['province'] = $gets['province'];
        }
        if ($gets['shop_name'] !=''){
            $where['shop_name'] = ['like','%'.$gets['shop_name'].'%'];
        }
        $province_list = Db::table('yf_shop')->field('province')->group('province')->order('id desc')->select();  //利用group方法去重
        $this->assign('province', $province_list);
        //获取店铺列表数据
        $shop_add = Db::table('yf_shop')->where($where)->order('id desc')->paginate(15,false, ['query' => $page_param]);
        //获取分页显示
        $list_info = $shop_add->toArray();
        $page = $shop_add->render();
        //模板变量赋值
        $this->assign('list', $list_info['data']);
        $this->assign('gets',$gets);
        $this->assign('total', $list_info['total']);
        $this->assign('page', $page);
        //渲染模板输出
        return $this->fetch();
    }

    /**
     * 店铺添加
     */
    public function shop_add(){
        if ($this->request->isPost()){
            $data['logo'] = input('param.logo',''); //店铺图标
            $data['province'] = input('param.pro',''); //省份
            $data['city'] = input('param.city',''); //城市
            $data['county'] = input('param.county',''); //地区
            $data['address'] = input('param.address',''); //详细地址
            $url= "http://restapi.amap.com/v3/geocode/geo?key=".config('map.webapi')."&address=".urlencode($data['address'])."&city=".urlencode($data['city']);
            $datas = file_get_contents($url);
            $content=strip_tags($datas);
            $content_arr=json_decode($content,true);
            if ($content_arr['infocode'] == '10000'){
                $location = explode(',',$content_arr['geocodes'][0]['location']);
                $data['lng'] = $location[0];//经度
                $data['lat'] = $location[1];//纬度
                $data['citycode'] = $content_arr['geocodes'][0]['citycode'];//所在城市代码
            }else{
                return json(['code'=>0,'msg'=>'获取地址经纬度信息有误']);
            }
            $data['shop_name'] = input('param.shop_name',''); //店铺名称
            $data['category'] = input('param.category',''); //店铺类型
            $data['is_self'] = input('param.is_self',1); //是否自营
            $data['shop_keeper'] = input('param.shop_keeper','admin');//店铺联系人 店长
            $data['phone'] = input('param.phone',0);//联系人电话
            $data['shop_phone'] = input('param.shop_phone','');//店铺座机
            $data['status'] = input('param.status',1);//店铺状态
            if ($data['lat'] == '' || $data['lng'] == '' || $data['address'] ==''){
                return json(['code'=>0,'msg'=>'店铺地址不能为空']);
            }
            if (ShopModel::shop_add($data)){
                return json(['code'=>200,'msg'=>'添加成功']);
            }else{
                return json(['code'=>0,'msg'=>ShopModel::getError()]);
            }

        }else{
            $items_cate = Db::table('yf_items_cate')->where(['status'=>1,'parent_id'=>0])->order('sort desc')->select();
            $this->assign('cate',$items_cate);
            // 渲染模板输出
            return $this->fetch();
        }

    }

    /**
     * 店铺编辑
     */
    public function shop_edit(){
        if ($this->request->isPost()){
            $data['id'] = input('param.id',0); //店铺名称
            if ($data['id'] == 0){
                return json(['code'=>0,'msg'=>'修改失败，店铺标识未传入']);
            }
            $data['logo'] = input('param.logo',''); //店铺图标
            $data['province'] = input('param.pro',''); //省份
            $data['city'] = input('param.city',''); //城市
            $data['county'] = input('param.county',''); //地区
            $data['address'] = input('param.address',''); //详细地址
            $url= "http://restapi.amap.com/v3/geocode/geo?key=".config('map.webapi')."&address=".urlencode($data['address'])."&city=".urlencode($data['city']);
            $datas = file_get_contents($url);
            $content=strip_tags($datas);
            $content_arr=json_decode($content,true);
            if ($content_arr['infocode'] == '10000'){
                $location = explode(',',$content_arr['geocodes'][0]['location']);
                $data['lng'] = $location[0];//经度
                $data['lat'] = $location[1];//纬度
                $data['citycode'] = $content_arr['geocodes'][0]['citycode'];//所在城市代码
            }else{
                return json(['code'=>0,'msg'=>'获取地址经纬度信息有误']);
            }

            $data['shop_name'] = input('param.shop_name',''); //店铺名称
            $data['category'] = input('param.category',''); //店铺类型
            $data['is_self'] = input('param.is_self',1); //是否自营
            $data['shop_keeper'] = input('param.shop_keeper','admin');//店铺联系人 店长
            $data['phone'] = input('param.phone',0);//联系人电话
            $data['shop_phone'] = input('param.shop_phone','');//店铺座机
            $data['status'] = input('param.status',1);//店铺状态
            if ($data['lat'] == '' || $data['lng'] == '' || $data['address'] ==''){
                return json(['code'=>0,'msg'=>'店铺地址不能为空']);
            }
            if (Db::table('yf_shop')->update($data)){
                return json(['code'=>200,'msg'=>'添加成功']);
            }else{
                return json(['code'=>0,'msg'=>ShopModel::getError()]);
            }

        }else{
            $shop_id = input('param.id',0);
            if ($shop_id == 0){
                $this->error('店铺标识有误');
            }
            $items_cate = Db::table('yf_items_cate')->where(['status'=>1,'parent_id'=>0])->order('sort desc')->select();
            $shop_info = Db::table('yf_shop')->where(['id'=>$shop_id])->find();
            if ($shop_info){
                $shop_info['logo'] = get_img_url($shop_info['logo']);
            }
            $this->assign('shop_info',$shop_info);
            $this->assign('cate',$items_cate);
            // 渲染模板输出
            return $this->fetch();
        }
    }

    /**
     * 店铺管理
     */
    public function ajax_getshops(){

        //获取店铺列表数据
        $shop_list = Db::table('yf_shop')->field('id,shop_name')->where('status',1)->order('id desc')->select();
        if ($shop_list){
            return json(['code'=>200,'data'=>$shop_list,'msg'=>'success']);
        }else{
            return json(['code'=>0,'msg'=>'暂无相关店铺信息']);
        }
    }

    /**
     * 店铺轮播
     */
    public function carousel_list(){
        $page_param = input('param.');
        if (isset($page_param['page']) && $page_param['page'] > 0)
            unset($page_param['page']);

        $carousel_list = Db::table('yf_carousel')->where(['shop_id'=>['neq',0]])->order('sort asc')->paginate(20, false, ['query' => $page_param]);
        //分页信息
        $page = $carousel_list->render();
        $carousel_list = $carousel_list->toArray();
        if ($carousel_list['data']){
            foreach ($carousel_list['data'] as $k=>$v){
                if ($v['cate'] ===1){
                    $carousel_list['data'][$k]['shop_name'] = Db::name('shop')->where(['id'=>$v['item_content']])->value('shop_name');
                }
                $carousel_list['data'][$k]['image'] = get_img_url($v['image']);
            }
        }
        //模板变量赋值
        $this->assign('list', $carousel_list['data']);
        $this->assign('total', $carousel_list['total']);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }
    /**
     * 轮播添加
     */
    public function carousel_add(){
        if ($this->request->isPost()){
            //开启事务
            Db::startTrans();
            try{
                $data['title'] = input('param.title',''); //轮播标题
                $data['position'] = input('param.position',0); //轮播展示位置
                $data['cate'] = input('param.cate',0); //类型
                $data['item_content'] = input('param.item_content',''); //类型内容
                $data['shop_id'] = input('param.shop_id',0); //所属店铺
                $data['image'] = input('param.image','');//图片地址
                $data['start_time'] = input('param.start_time',0);//开始时间
                $data['end_time'] = input('param.end_time',0);//结束时间
                $data['status'] = input('param.status',0);//状态
                if ($data['position'] == 0){
                    throw new Exception('请选择投放的位置');
                }
                if ($data['shop_id'] == 0){
                    throw new Exception('请选择要投放的店铺');
                }
                if ($data['cate'] == 4){
                    $data['couponurl'] = input('param.couponurl','');//商品优惠券
                }
                if ($data['cate'] == 0){
                    throw new Exception('类型未选择');
                }
                if ($data['cate'] !=3 & $data['item_content'] == ''){
                    if ($data['cate'] = 1){
                        throw new Exception('请选择店铺');
                    }elseif ($data['cate'] = 2){
                        throw new Exception('网址链接未填');
                    }elseif ($data['cate'] = 4){
                        throw new Exception('淘宝/天猫商品id未设置');
                    }
                }
                if ($data['image'] == ''){
                    throw new Exception('封面图未上传');
                }
                if ($data['start_time'] == 0){
                    throw new Exception('开始时间未设置');
                }
                if ($data['end_time'] == 0){
                    throw new Exception('结束展示时间未设置');
                }
                $data['start_time'] = date_to_unixtime( $data['start_time']);
                $data['end_time'] = date_to_unixtime( $data['end_time']);
                $data['add_time'] = time();//结束时间
                $data['sort'] = 50;//排序
                $id = Db::table('yf_carousel')->insertGetId($data);
                if ( $data['cate'] == 3){
                    Db::table('yf_carousel')->where('carousel_id',$id)->setField('item_content',$id);
                }
                //事务提交
                Db::commit();
                return json(['code'=>200,'msg'=>'success']);
            }catch (Exception $e){
                //事务回滚
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
           $shop_list =  Db::name('shop')->field('id,shop_name')->where(['status'=>1])->select();
           $this->assign('shops',$shop_list);
            // 渲染模板输出
            return $this->fetch();
        }
    }

    /**
     * 轮播编辑
     */
    public function carousel_edit(){
        if ($this->request->isPost()){
            //开启事务
            Db::startTrans();
            try{
                $data['carousel_id'] = input('param.carousel_id',''); //轮播id
                $data['title'] = input('param.title',''); //轮播标题
                $data['cate'] = input('param.cate',0); //类型
                $data['item_content'] = input('param.item_content',''); //类型内容
                $data['shop_id'] = input('param.shop_id',0); //所属店铺
                $data['image'] = input('param.image','');//图片地址
                $data['start_time'] = input('param.start_time',0);//开始时间
                $data['end_time'] = input('param.end_time',0);//结束时间
                $data['status'] = input('param.status',0);//状态
                if ($data['cate'] == 0){
                    throw new Exception('类型未选择');
                }
                if ($data['shop_id'] == 0){
                    throw new Exception('请选择要投放的店铺');
                }
                if ($data['item_content'] == ''){
                    throw new Exception('类型未选择');
                }
                if ($data['image'] == ''){
                    throw new Exception('封面图未上传');
                }
                if ($data['start_time'] == 0){
                    throw new Exception('开始时间不能为空');
                }
                if ($data['end_time'] == 0){
                    throw new Exception('结束时间不能为空');
                }
                $data['start_time'] = date_to_unixtime( $data['start_time']);
                $data['end_time'] = date_to_unixtime( $data['end_time']);
                Db::table('yf_carousel')->update($data);
                //事务提交
                Db::commit();
                return json(['code'=>200,'msg'=>'success']);
            }catch (Exception $e){
                //事务回滚
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            $shop_list =  Db::name('shop')->field('id,shop_name')->where(['status'=>1])->select();
            $this->assign('shops',$shop_list);
            $carousel_info=Db::name('carousel')->where(array('carousel_id'=>input('carousel_id')))->find();
            if ($carousel_info){
                $carousel_info['host_image'] = get_img_url($carousel_info['image']);
                $carousel_info['str'] = '<input type="text"class="input-text"  name="item_content" value="'.$carousel_info['item_content'].'" placeholder="请输入要链接的网址">';
            }
            $this->assign('data',$carousel_info);
            // 渲染模板输出
            return $this->fetch();
        }
    }



}
